package cn.td0f7.android.wangzhongcourse.contentprovider;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;

import cn.td0f7.android.wangzhongcourse.R;

public class ContentProviderActivity extends AppCompatActivity {
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_provider);
        uri = Uri.parse("content://cn.td0f7.app.android.providers.myprovider/user");
        getMsgs();
        try {
            addContact();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        insertContentProvider();
    }

    private void insertContentProvider() {
        ContentValues values = new ContentValues();
        values.put("name", "推动学堂");

        getContentResolver().registerContentObserver(uri, true, new MyObserver(new Handler()));

        getContentResolver().insert(uri, values);

        getContentResolver().update(uri, values, "_id=?", new String[]{"3"});
    }

    private void addContact() throws RemoteException, OperationApplicationException {
        //使用事务添加联系人，有一条失败则全失败
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri = Uri.parse("content://com.android.contacts/data");

        ContentResolver resolver = getContentResolver();
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
        ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)
                .withValue("account_name", null)
                .build();
        operations.add(op1);

        //依次是姓名，号码，邮编
        ContentProviderOperation op2 = ContentProviderOperation.newInsert(dataUri)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/name")
                .withValue("data2", "夏洛")
                .build();
        operations.add(op2);

        ContentProviderOperation op3 = ContentProviderOperation.newInsert(dataUri)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/phone_v2")
                .withValue("data1", "18310035566")
                .withValue("data2", "2")
                .build();
        operations.add(op3);

        ContentProviderOperation op4 = ContentProviderOperation.newInsert(dataUri)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/email_v2")
                .withValue("data1", "1363636552@qq.com")
                .withValue("data2", "2")
                .build();
        operations.add(op4);

        resolver.applyBatch("com.android.contacts", operations);
    }

    //读取短信
    private void getMsgs() {
        Uri uri = Uri.parse("content://sms/");
        ContentResolver resolver = getContentResolver();
        //{"address","date","body"}代表获取的是哪些列的信息，当前我只获取了三个
        Cursor cursor = resolver.query(uri, new String[]{"address", "date", "body"}, null, null, null);
        while (cursor.moveToNext()) {
            String address = cursor.getString(0);
            String date = cursor.getString(1);
            String body = cursor.getString(2);
            System.out.println("地址:" + address);
            System.out.println("时间:" + date);
            System.out.println("内容:" + body);
            System.out.println("===========分隔符===========");
        }
        cursor.close();
    }

    class MyObserver extends ContentObserver {

        /**
         * Creates a content observer.
         *
         * @param handler The handler to run {@link #onChange} on, or null if none.
         */
        public MyObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    String id = cursor.getString(cursor.getColumnIndex("_id"));
                    Log.d("用户名称", name + "   " + id);
                }
            }
        }
    }
}